<template>
  <div class="createPost-container">
    <el-form :model="form" :rules="rules" label-width="120px" ref="goodsForm">
      <el-tabs type="border-card">
        <el-tab-pane label="基础资料">
          <div class="createPost-main-container">
            <el-row>
              <el-col :span="24">
                <el-form-item style="margin-bottom: 40px;" prop="name" required="" label="名称:">
                  <MDinput v-model="form.name" :maxlength="100"  name="name" required>
                    商品名称
                  </MDinput>
                </el-form-item>

                <div class="postInfo-container">
                  <el-row>
                    <el-col :span="18">
                      <el-form-item label-width="100px" label="分类:" class="postInfo-container-item">
                          <el-cascader
                              :options="cateTree"
                              v-model="default_select"
                              :props="{ checkStrictly: true ,label:'name',value:'id'}"
                              clearable>
                          </el-cascader>
                      </el-form-item>
                    </el-col>
                    <el-col :span="6"></el-col>
                  </el-row>
                </div>
              </el-col>
            </el-row>

            <el-form-item style="margin-bottom: 40px;" label-width="100px" label="品牌:">
             <el-select v-model="form.brand_id"  filterable default-first-option remote placeholder="选择品牌">
               <el-option v-for="(item,index) in brands"  :label="item.name" :value="item.id" />
             </el-select>
            </el-form-item>

            <el-form-item style="margin-bottom: 40px;" label-width="100px" label="简介:">
              <el-input v-model="form.intro" :rows="1" type="textarea" class="article-textarea" autosize placeholder="请添加商品简介信息" />
              <span v-show="contentShortLength" class="word-counter">{{ contentShortLength }}words</span>
            </el-form-item>

            <el-form-item style="margin-bottom: 40px;" label-width="100px" label="分享描述:">
              <el-input v-model="form.share_intro" :rows="1" type="textarea" class="article-textarea" autosize placeholder="请添加分享描述信息" />
              <span v-show="contentShareLength" class="word-counter">{{ contentShareLength }}words</span>
            </el-form-item>

            <el-form-item label="商品主图" prop="images" required="">
              <img v-for="(item,index) in form.images" :src="item.url" class="avatar">
              <i @click="showImageCenter" class="el-icon-plus avatar-uploader-icon"></i>
            </el-form-item>

            <el-form-item label="选择标签" prop="tags">
                <el-checkbox-group v-model="form.tag_value" @change="handleCheckedTagChange">
                  <el-checkbox v-for="value in tags" :label="value.id" :key="value.id">{{value.name}}</el-checkbox>
                </el-checkbox-group>
            </el-form-item>

            <el-row>
              <el-col :span="8">
                <el-form-item label="商品单位" prop="unit">
                  <el-input v-model="form.unit" />
                </el-form-item>
              </el-col>

              <el-col :span="10">
                <el-form-item label="排序" prop="sort">
                  <el-input v-model="form.sort" type="number" />
                </el-form-item>
              </el-col>
            </el-row>


            <el-form-item label="是否包邮" prop="is_postage">
              <el-switch
                v-model="form.is_postage"
                active-color="#13ce66"
                inactive-color="#ff4949">
              </el-switch>
            </el-form-item>


            <el-form-item>
              <el-button type="primary" @click="onSubmit('goodsForm')">保 存</el-button>
            </el-form-item>
          </div>

          <ImageCenter :is_multiple=false :Innervisible.sync="dialogImageVisible" :limit="limit"  @change="changeImage" @closeImage="closeImage"/>
        </el-tab-pane>
        <el-tab-pane label="规格库存">
          <el-form-item  prop="spec_type" required>
            <el-switch
              v-model="form.spec_type"
              active-text="多规格"
              inactive-text="单规格">
            </el-switch>
          </el-form-item>

          <el-row v-if="!form.spec_type">
            <el-row><el-col :span="8">
              <el-form-item style="margin-bottom: 40px;" label-width="100px" label="商品编码:" prop="bn" required>
                  <el-input v-model="form.bn" />
              </el-form-item>
            </el-col></el-row>

              <el-row>
                <el-col :span="8">
                  <el-form-item label-width="100px" label="总库存:" class="postInfo-container-item" required>
                     <el-input v-model="form.stock" type="number"/>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label-width="100px" label="库存报警:" class="postInfo-container-item" required>
                     <el-input v-model="form.stock_warning" type="number"/>
                  </el-form-item>
                </el-col>
              </el-row>

            <el-col :span="8">
              <el-form-item label-width="100px" prop="retail_price" label="销售价:" class="postInfo-container-item" required>
                 <el-input v-model="form.retail_price" type="number"/>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label-width="100px" prop="market_price" label="市场价:" class="postInfo-container-item"  required>
                 <el-input v-model="form.market_price" type="number"/>
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label-width="100px" prop="cost_price" label="成本价:" class="postInfo-container-item" required>
                 <el-input v-model="form.cost_price" type="number"/>
              </el-form-item>
            </el-col>
          </el-row>

          <div v-else>
          <el-row>
            <el-form-item label-width="100px" prop="spec_id" label="规格类型:" class="postInfo-container-item" >
              <el-select v-model="form.attr_id"  filterable default-first-option remote placeholder="选择类型" @change="selectAttr()">
                <el-option v-for="(item,index) in attr"  :label="item.title" :value="item.id" />
              </el-select>
            </el-form-item>


          </el-row>
          <el-row v-for="(item,index) in attrList">
            <el-form-item label-width="100px" :prop="'attr_'+item.id"  :label="item.title" class="postInfo-container-item" >
              <el-input v-model="item.value" v-if="item.type == 1"/>
             <el-checkbox-group v-else-if="item.type == 3" v-model="item.select" >
                <el-checkbox v-for="value in item.value" :label="value" >{{value}}</el-checkbox>
              </el-checkbox-group>
              <el-radio-group v-else v-model="item.check">
                  <el-radio v-for="value in item.value" :label="value" >{{value}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-row>
          <el-divider></el-divider>

          <el-table  :data="specList"   style="width: 100%">
              <el-table-column label="规格名" prop="title" width="180"> </el-table-column>
              <el-table-column label="规格项">
                <template slot-scope="scope">
                 <div v-for="(v, i) in scope.row.spec_value"  class="spec_btn">
                   <el-button :type="v.checked==1 ? 'primary' : ''"  size="small" @click="handleChecekedSpec(v,i, scope.row)">{{v.title}}</el-button>
                   <el-color-picker v-model="v.data" size="small" v-if="scope.row.show_type == 2">颜色</el-color-picker>
                   <el-button  size="small" v-else-if="scope.row.show_type == 3">图片</el-button>
                 </div>
                </template>
              </el-table-column>
            </el-table>
            <el-divider></el-divider>
            <el-table  :data="specTableRow"   style="width: 100%">
              <el-table-column :label="row.name" v-for="(row, key) in tableColumn">
                <template slot-scope="scope">
                 <span v-if="row.type == 'text'">{{scope.row[row.key]}}</span>
                 <el-input v-model="scope.row[row.key]" :prop="row.key" v-else-if="row.type == 'input'" required/>
                 <el-select v-model="scope.row[row.key]" placeholder="请选择" v-else-if="row.type == 'select'">
                   <el-option
                     v-for="(item, index) in statusOptions"
                     :key="item.id"
                     :label="item.name"
                     :value="item.id">
                   </el-option>
                 </el-select>
                 <i class="el-icon-picture-outline" style="font-size: 2rem;" v-else></i>
                </template>
              </el-table-column>
            </el-table>
          </div>

          <el-form-item>
            <el-button type="primary" @click="onSubmit('goodsForm')">保 存</el-button>
          </el-form-item>
        </el-tab-pane>

        <el-tab-pane label="商品详情">
          <el-form-item prop="content" style="margin-bottom: 30px;">
            <markdown-editor ref="markdownEditor" v-model="form.details" height="400px" />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="onSubmit('goodsForm')">保 存</el-button>
          </el-form-item>
        </el-tab-pane>
      </el-tabs>
    </el-form>
  </div>
</template>

<script>
  import {createIndex,updateGoods,detailGoods,init,detail} from '@/api/goods/goods'
  import MDinput from '@/components/MDinput'
  import ImageCenter from '@/components/ImageCenter'
  import MarkdownEditor from '@/components/MarkdownEditor'
export default {
  components: { MDinput, ImageCenter,MarkdownEditor},
  computed: {
    contentShortLength() {
      return this.form.intro.length
    },
    contentShareLength() {
      return this.form.share_intro.length
    }
  },
  data() {
    return {
      is_update:false,
      dataInfo: {
        id: [],
        name: []
      },
      form: {
        name: '', // 标题
        show_type: '',
        spec_name: [],
        tag_value:[],
        spec_sort: 1,
        sort: '', // 排序
        explain: '',
        details:'',
        content_short:'',
        is_postage:true,
        images:[],
        spec_type:0,
        attr_id:0,
        intro:'', // 简介
        share_intro:'', // 分享 简介
      },
      limit:5,
      tags:[],
      brands:[],
      default_select:[],
      cateTree:[],
      attr:[],
      attrList:[],
      specList:[],
      selectSpec:[],
      specValueList:[],
      specColumn:[],
      specTableRow:[],
      dialogImageVisible:false,
      tableColumn: [
        {name:'sku图片',key:'img',type:'image'},
        {name:'零售价格',key:'retail_price',type:'input'},
        {name:'成本价格',key:'cost_price',type:'input'},
        {name:'市场价格',key:'market_price',type:'input'},
        {name:'库存',key:'stock',type:'input'},
        {name:'BN编码',key:'pbn',type:'input'},
        {name:'条码',key:'barcode',type:'input'},
        {name:'重量',key:'weight',type:'input'},
        {name:'初始销量',key:'initial_sales',type:'input'},
        {name:'启用状态',key:'status',type:'select'},
      ],
      goodsCate:['1级分类','2级分类','3级分类'],
      statusOptions:[{id:1,name:'启用'},{id:0,name:'禁用'}],
      rules:{
        title:[{required: true, message: '名称不能为空', trigger: 'blur' }],
        show_type:[{required: true, message: '请选择类型', trigger: 'blur' }],
      }
    }
  },
  beforeMount() {
    let id = this.$route.params.id || 0;
    this.init_goods(id)

  },
  methods: {
    async init_goods(id){
      await init().then(response=>{
         this.tags = response.data.tags
         this.cateTree = response.data.cate
         this.brands = response.data.brand
         this.attr = response.data.attr

         if(id > 0) this.init_detail(id);
      })
    },
    init_detail(id){
      this.is_update = true
      detail(id).then(response => {
        let _base = response.data.base
        let _detail = response.data.detail
        let _goods_attr_val = response.data.goods_attr_val
        let _goods_spec_val = response.data.goods_spec_val
        let _goods_products = response.data.product

        this.form = _base;
        this.form.attr_id = _base.type_id

        this.form.images = [];
        if(_base.images_copy && _base.images_copy.length){
          _base.images_copy.map(e=>{
            this.form.images.push({url:e})
          })
        }
        this.form.tag_value = _base.tags.split(',').map(re=>{return parseInt(re)})

        // 默认选中选项 品牌、分类 属性
        this.default_select = this.form.cate
        this.form.details = _detail.details
        this.form.is_postage = this.form.is_postage == 1 ? true : false
        this.form.spec_type = this.form.spec_type == 1 ? true : false

        // 初始化 属性
        if(this.form.spec_type){
          this.form.attr_id = this.form.type_id
          this.selectAttr(_goods_attr_val, _goods_spec_val,_goods_products)
        }

        // 初始化 规格、货品sku
      })
    },
    handleCheckedTagChange(){

    },
    selectAttr(_goods_attr_val, _goods_spec_val,_goods_products){
      let _attr = this.attr.map(e=>{
        if(e.id == this.form.attr_id){
          this.attrList = e.attr
          this.specList = e.spec
        }
      })

       if(_goods_attr_val && _goods_attr_val.length){
        this.attrList.map(g=>{
          _goods_attr_val.map(f=>{
            if(g.id == f.base_attribute_value_id){
              if(g.type == 1) g.value = f.value
              else if (g.type == 2) g.check = f.value
              else g.select = f.value ? f.value.split(',') : []
            }
          })
        })
      }

      if(_goods_spec_val && _goods_spec_val.length){
        this.specList.map((g, i)=>{
          if(g.spec_value && g.spec_value.length){
            g.spec_value.map((e,m)=>{
              _goods_spec_val.map(f=>{
                if(e.id == f.base_spec_value_id) {
                  //e.checked = 1;e.data=f.data;
                  this.handleChecekedSpec(e,m, g,_goods_products)
                }
              })
            })
          }
        })
      }
    },
    handleChecekedSpec(spec, i, row, _goods_products){
      let _indexS = this.specList.indexOf(row)
      let _is_exists = false;
      this.selectSpec.map(e=>{
        if (e.spec_value && e.spec_value.length){
          e.spec_value.map(f=>{
            if (f.id == spec.id){
              _is_exists = true;
            }
          })
        }
      })

      if(!_is_exists){
        if(!this.selectSpec[_indexS]){
          let _val = this.specList[_indexS];
          this.selectSpec[_indexS] = {id:_val.id,title:_val.title,show_type:_val.show_type,spec_value:[]}
        }
        this.selectSpec[_indexS]['spec_value'].push(spec)
        this.specList[_indexS]['spec_value'][i].checked = 1
        //this.selectSpec.push(spec)
      }else{
        this.specList[_indexS]['spec_value'][i].checked = 0
        let _index = this.selectSpec[_indexS]['spec_value'].indexOf(spec)
        this.selectSpec[_indexS]['spec_value'].splice(_index, 1)
        if(this.selectSpec[_indexS]['spec_value'].length == 0){this.selectSpec.splice(_indexS, 1)}
      }

      this.makeTable(_goods_products);
    },
    showImageCenter() {
      this.dialogImageVisible = true;
      return false;
    },
    makeTable:function(_goods_products){
      this.specTableRow = [];

      if(this.selectSpec.length <=0) return false;
      let _for_select_spec = [];
      this.selectSpec.map((item, index)=>{
        _for_select_spec.push(item)
        let _row = {key:'spec_'+item.id,name:item.title,type:'text'}

        let _is_exists = false;
        this.tableColumn.map(f=>{
          if(f.key == _row.key) _is_exists = true;
        })
        if(!_is_exists){
          this.tableColumn.splice(index,0,_row)
        }
      })

      let _now_index=0;
      let _value1 = _for_select_spec[_now_index]['spec_value']

      for (let i=0; i <_value1.length ; i++) {
      	let _id = [_value1[i]['id']];
      	let _name = [_value1[i]['title']];

        let _row  = {img:'',retail_price:'',cost_price:'',market_price:'',stock:'',pbn:'',barcode:'',weight:'',initial_sales:'',status:1};
        
        _row['spec_'+_for_select_spec[_now_index]['id']] = _value1[i]['title'];
        this.getNode(_id, _name, _now_index, _for_select_spec, _row, _goods_products);
      }

     // console.log(this.specTableRow)

    },
    getNode(id,name,Pindex,_for_select_spec, _row, _goods_products){
      let _now_index = Pindex + 1;
      if( "undefined" != typeof _for_select_spec[_now_index] ){
        const _value =  _for_select_spec[_now_index]['spec_value']

        for(let k=0;k<_value.length;k++){
            let _id = JSON.parse(JSON.stringify(id));
            let _name = JSON.parse(JSON.stringify(name));
            let _row_temp = {}
            _row_temp = JSON.parse(JSON.stringify(_row))

            _id.push(_for_select_spec[_now_index]['spec_value'][k]['id'])
            _name.push(_for_select_spec[_now_index]['spec_value'][k]['title'])

            let spec_key = 'spec_'+_for_select_spec[_now_index]['id'];
            _row_temp[spec_key] = _for_select_spec[_now_index]['spec_value'][k]['title'];

            this.getNode(_id,_name,_now_index, _for_select_spec, _row_temp,_goods_products);
        }
      }else{
        _row._id = id.sort((a,b)=>{return a-b;}).join('-')
        _row._name = name.join(' ')

        let product = [];
        if(_goods_products && _goods_products.length){
          product = _goods_products.filter(item=>item.spec_ids==_row._id) || []

          if( product[0] instanceof Object){
            _row.id = product[0].id;
            _row.img = product[0].img;
            _row.retail_price = product[0].retail_price;
            _row.cost_price =product[0].cost_price
            _row.market_price = product[0].market_price;
            _row.stock = product[0].stock;
            _row.pbn = product[0].pbn;
            _row.barcode = product[0].barcode;
            _row.weight = product[0].weight;
            _row.initial_sales = product[0].initial_sales;
            _row.status = product[0].is_up;
          }
        }

        this.specTableRow.push(_row)
      }
    },
    changeImage:function(res){
      this.dialogImageVisible = false;
      this.form.images = res
    },
    closeImage:function(){
      this.dialogImageVisible = false;
    },
    onSubmit(formName) {
      this.$refs[formName].validate((valid)=>{
        if (valid) {
          this.checkSpec()
          let id = this.$route.params.id || 0;

          let _data = {}
          this.form.category_id = this.default_select;
          _data.base = this.form
          _data.attr = this.attrList
          _data.spec = this.specTableRow
          _data.specList = this.specList

          _data.base.spec_type = _data.base.spec_type  ? 1 : 0

          let _tag = this.checkSub();
          if(!_tag){ return false;}
          if(id > 0){
            updateGoods(_data, id).then(response => {
              if(response.code == 200){
                this.$message({
                  message: '操作成功',
                  type: 'success'
                })
                setTimeout(()=>{
                  this.$router.push({name:'goodsList'});
                }, 500)
              }
            })
          }else{
            createIndex(_data).then(response => {
              if(response.code == 200){
                this.$message({
                  message: '操作成功',
                  type: 'success'
                })
                setTimeout(()=>{
                  this.$router.push({name:'goodsList'});
                }, 500)
              }
            })
          }
        }
      })
    },
    checkSub(){
      // 提交前的数据检测
      if (this.default_select.length < 1){
        return this.showTipsError('请选择商品分类');
      }

      if (this.form.images.length < 1){
        return this.showTipsError('请至少上传一张图片');
      }

      if(this.form.spec_type && this.specTableRow.length < 1){
        return this.showTipsError('请选择规格项');
      }

      return true;
    },
    showTipsError(message){
      this.$message({
        message: message,
        type: 'warning'
      })

      return false;
    },
    checkSpec(){
      /* let _spec_name = this.form.spec_name
      if (!_spec_name || _spec_name.length<1) {
        this.$message({
          message: '规格值不能为空',
          type: 'warning'
        })
        return false;
      }
      let _name = []
      let _empty = false
      _spec_name.map(v=>{_name.push(v.value);if(v.value == '' || !v.value){_empty = true}})

      if(_name.length < 1 || _empty){
        this.$message({
          message: '规格值不能为空',
          type: 'warning'
        })
        return false;
      }else{
        console.log(_name)
      } */
    },
    onCancel() {
      this.$message({
        message: 'cancel!',
        type: 'warning'
      })
    },
    addName() {
      this.form.spec_name.push({
        id:0,
        value: '',
        sort: 1,
        key: Date.now()
      });
    },
    removeName(item) {
      var index = this.form.spec_name.indexOf(item)
      if (index !== -1) {
        this.form.spec_name.splice(index, 1)
      }
    },
  }
}
</script>

<style lang="scss" scoped>
  @import "~@/styles/mixin.scss";
.line{
  text-align: center;
}

.createPost-container {
  *{font-size:12px;}
  position: relative;

  .createPost-main-container {
    padding: 40px 45px 20px 50px;

    .postInfo-container {
      position: relative;
      @include clearfix;
      margin-bottom: 10px;

      .postInfo-container-item {
        float: left;
      }
    }
  }

  .word-counter {
    width: 40px;
    position: absolute;
    right: 10px;
    top: 0px;
  }
}
.article-textarea ::v-deep {
  textarea {
    padding-right: 40px;
    resize: none;
    border: none;
    border-radius: 0px;
    border-bottom: 1px solid #bfcbd9;
  }
}
.avatar{width: 90px;height: 90px;border: 1px solid #ccc;padding: 1px;margin-right: 12px;float: left;}
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 90px;
    height: 90px;
    line-height: 90px;
    text-align: center;
    border:1px solid #ccc;
  }
  .spec_btn{float: left;margin-right: 0.1rem;display: inline-block;}
  .spec_row{margin-bottom: 1.375rem;}
</style>
